package org.tema1;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;


import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

class City implements Comparable<City>
{
    public String cityName;
 
    @Override
    public String toString ()
    {
        return cityName;
    } 

    public int compareTo(City oras)
    {
    	 return this.cityName.compareToIgnoreCase(oras.cityName);
    }

}
 
class CitiesAdapter extends BaseAdapter
{
	private Activity context;
	ArrayList<City> cities;
 
	public CitiesAdapter (Activity _context)
	{
		this.context = _context;
		cities = new ArrayList<City>();
	}
 
	public View getView (int position, View convertView, ViewGroup list) 
	{
		// functia trebuie sa intoarca view-ul de pe pozitia position din lista
		// convertView este un element din lista ce nu mai este vizibil si poate fi convertit
		View element;
		
		if (convertView == null)
        {
			LayoutInflater inflater = context.getLayoutInflater();
			element = inflater.inflate(R.layout.oras, null);
        }
		else
			element = convertView;
 
		TextView nume = (TextView)element.findViewById(R.id.nume_oras);
 
		nume.setText(cities.get(position).cityName);
 
		return element;
	}
 
    public int getCount ()
    {
		// intaorce nr de elemente din lista
        return cities.size ();
	}
 
	public Object getItem(int position) 
	{
		// intoarce elementul de pe pozitia position din model
		return cities.get(position);
	}
 
	public long getItemId(int position) 
	{
		// fiecare element din lista poate avea un id, nu este insa obligatoriu
		return 0;
	}
 
    public void addCity (String cityName)
    {
          City c = new City();
          c.cityName = cityName;
          
          int pos;
          for(pos=0;pos<cities.size();pos++)
          {
        	  if (c.compareTo(cities.get(pos)) < 0)
        		  break;
          }
          cities.add(pos, c);
          
          // acesta functie deterimina adaptorul sa ceara listei sa reafiseze continutul
          this.notifyDataSetChanged();
    }
    
    public boolean removeCity (int position)
    {
    	if (position >= cities.size())
    		return false;
    	cities.remove(position);
    	this.notifyDataSetChanged();
    	return true;
    }
    
    public String getCitiesNames()
    {
    	String orase = "";
    	for(int i=0;i<cities.size();i++)
    		orase += cities.get(i).cityName+"\n";
    	return orase;
    }
}

public class WeatherActivity extends ListActivity {
	
	CitiesAdapter adapter;
	Button addCity;
    public static final String LIST = "CityList.txt";
    public static final String PATH = "http://www.google.com/ig/api?weather=";
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        adapter = new CitiesAdapter(this);
        addCity = (Button)findViewById(R.id.add);
        setListAdapter(adapter);
        
        try {
	    	InputStream in = openFileInput(LIST);
	    	if (in != null) {
		    	InputStreamReader tmp = new InputStreamReader(in);
		    	BufferedReader reader = new BufferedReader(tmp);
		    	String buf;
 
		    	while((buf = reader.readLine()) != null) {
		    		adapter.addCity(buf.toString());
		    	}
		    	in.close();
	    	}
    	} catch (java.io.FileNotFoundException e) {
    		// that's OK, we probably haven't created it yet
    	} catch (Throwable t) {
    	Toast.makeText(this, "Exception: " + t.toString(), 2000).show();
    	}
        
        addCity.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// construim un Intent
		        Intent intent = new Intent ();
		        intent.setClass(WeatherActivity.this, AddCityActivity.class);
		        startActivityForResult(intent, 1);
			}
		});
        
        getListView().setOnItemLongClickListener(new OnItemLongClickListener() 
		{
 
			public boolean onItemLongClick(AdapterView<?> listAdapter, View view, int position, long id) 
			{
				return adapter.removeCity(position);
			}
		});
    }
	
	 @Override
	 protected void onStop(){
	    super.onStop();

    	try {
	    	OutputStreamWriter out = new OutputStreamWriter(openFileOutput(LIST, 0));
	    	out.write(adapter.getCitiesNames());
	    	out.close();
    	} catch (Throwable t) {
    	Toast.makeText(this, "Exception: " + t.toString(), 2000).show();
    	}
	}
    
    @Override
    public void onActivityResult (int requestCode, int responseCode, Intent data)
    {
    	if (requestCode == 1)
    	{
    		// s-a apasat butonul OK
    		if (responseCode==1)
    		{
    			String oras = data.getStringExtra("oras");
    			adapter.addCity (oras);
    		}
    		// s-a apasat butonul Cancel
    		else if (responseCode==0)
    		{
    		}
    	}
    }
    
    @Override
    public void onListItemClick (ListView list, View v, int position, long id)
    {
        City nume_oras = (City)adapter.getItem (position);
		// construim un Intent
        Intent intent = new Intent ();
        intent.setClass(WeatherActivity.this, DetailsActivity.class);
        intent.putExtra("nume_oras", nume_oras.cityName);
        startActivity(intent);
    }
}